package com.bilicute.libman.exception;

import com.bilicute.libman.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author i囡漫笔
 * @description 全局报错输出
 * @date 2024/4/16
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * @param e:  [e] 错误详情
     * @return Result
     * @author iNMB
     * @description 全局报错输出以api形式反馈
     * @date 2024/4/16
     */
    @ExceptionHandler (Exception.class )
    public Result<String> handleException(Exception e){
        String patternStr = "default message \\[(.*?)]";
        Pattern pattern = Pattern.compile(patternStr);
        String exceptionMessage = e.getMessage();
        Matcher matcher = pattern.matcher(exceptionMessage);

        // 存储所有匹配项的列表
        List<String> matches = new ArrayList<>();

        // 循环查找所有匹配项
        while (matcher.find()) {
            // 将匹配到的内容添加到列表中
            matches.add(matcher.group(1));
        }

        e.printStackTrace();

        // 如果没有匹配到内容，则输出原始字符串
        if (matches.isEmpty()) {
            return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage():"操作失败");
        } else {
            String result = String.join(", ", matches);
            return Result.error(result);
        }
    }
}
